import { Component, } from 'react'
import { View, Text, Form, Input, Picker, Button, Textarea, Image, ScrollView, Label, CheckboxGroup, Checkbox } from '@tarojs/components'
import Taro from '@tarojs/taro'
import dayjs from 'dayjs'
import './index.scss'

// 高阶函数：创建字段显示条件判断
const createConditionChecker = ({ state, value }) => {
    const { businessType, invoiceType, customerType, key2, key8, key10, key14, key19 } = state
    const { key } = value
    if (key === 'cheshangyueNo') {
        console.log(key, businessType)
        return ['整车销售', '整车调拨', '售后维修'].includes(businessType)
    } else if (key === 'originalInvoice') {
        return ['重新开票',].includes(invoiceType)
    }
    else if (key === 'customerType') {
        return ['整车销售',].includes(businessType)
    }
    else if (key === 'mobile' || key === 'idCard') {
        return ['个人',].includes(customerType)
    }
    else if (key === 'businessLicense') {
        return ['公司',].includes(customerType)
    } else if (key === 'key1') {
        return ['整车销售', '整车调拨'].includes(businessType)
    } else if (key === 'key2') {
        return ['整车销售',].includes(businessType)
    } else if (key === 'key3') {
        return ['委托开票单位-内部单位', '委托开票_内部_他店车源',].includes(key2)
    } else if (key === 'key4') {
        return ['委托开票_外部',].includes(key2)
    } else if (key === 'key5') {
        return ['托开票单位-内部单位', '委托开票_内部_他店车源', '委托开票_外部',].includes(key2)
    } else if (key === 'key7') {
        return ['衍生业务',].includes(businessType)
    } else if (key === 'key8') {
        return ['整车销售',].includes(businessType)
    } else if (key === 'key9') {
        return ['是',].includes(key8)
    } else if (key === 'key10') {
        return ['整车销售',].includes(businessType)
    } else if (key === 'key11') {
        return ['是',].includes(key10)
    } else if (key === 'key12') {
        return ['整车销售',].includes(businessType)
    } else if (key === 'key13') {
        return ['售后维修',].includes(businessType)
    } else if (key === 'key14') {
        return ['售后维修',].includes(businessType)
    } else if (key === 'key15') {
        return ['是',].includes(key14)
    } else if (key === 'key16') {
        return ['索赔开票',].includes(businessType)
    } else if (key === 'key17') {
        return ['精品配件',].includes(businessType)
    } else if (key === 'key18') {
        return ['其他业务',].includes(businessType)
    } else if (key === 'key20' || key === 'key21' || key === 'key23' || key === 'key24' || key === 'key25' || key === 'key26') {
        return !key19
    }

    return true
}

// 表单配置数组
const formConfig = [
    {
        section: '开票资料收集表',
        fields: [
            {
                key: 'canpyName',
                label: '申请单位',
                type: 'input',
                required: true,
            },
            {
                key: 'businessType',
                label: '业务类型',
                type: 'picker',
                options: ['整车销售', '整车调拨', '售后维修', '索赔开票', '衍生业务', '精品配件', '其他业务', '资产处置'],
                aboutKey: ['cheshangyueNo', 'customerType'],
                required: true
            },
            {
                key: 'money',
                label: '开票金额',
                type: 'input',
                required: true
            },
            {
                key: 'cheshangyueNo',
                label: '车商悦单据号',
                type: 'input',
                required: true
            },
            {
                key: 'invoiceType',
                label: '开票类型',
                aboutKey: ['originalInvoice',],
                type: 'picker',
                options: ['当期开票', '前期补充开票', '提前开票', '重新开票'],
                required: true
            },
            {
                key: 'originalInvoice',
                label: '原发票',
                type: 'upload',
            },
            {
                key: 'customerType',
                label: '个人/公司',
                type: 'picker',
                options: ['个人', '公司'],
            },
            {
                key: 'mobile',
                label: '客户联系电话',
                type: 'input',
                required: true
            },
            {
                key: 'idCard',
                label: '身份证',
                type: 'idCardUpload',
                required: true
            },
            {
                key: 'businessLicense',
                label: '营业执照',
                type: 'upload',
                required: true
            },


            {
                key: 'VIN',
                label: '车辆识别代码/车架号码(VIN)',
                type: 'picker',
                options: ['1', '2'],
                required: true,
                defaultValue: [18]
            },

            {
                key: 'key1',
                label: '车辆合格证',
                required: true,
                type: 'ocrImageUpload',
            },


            {
                key: 'key2',
                label: '开票类型(DK)',
                type: 'picker',
                options: ['自店开票', '委托开票_内部_自店车源', '委托开票_内部_他店车源', '委托开票_外部'],
                required: true,
            },


            {
                key: 'key3',
                label: '委托开票单位-内部单位',
                type: 'picker',
                options: ['单位1', '单位2'],
                required: true,
            },


            {
                key: 'key4',
                label: '委托开票单位-外部单位',
                type: 'picker',
                options: ['单位1', '单位2'],
                required: true,
            },

            {
                key: 'key5',
                label: '委托开票金额（专票）',
                type: 'input',
                required: true
            },
            {
                key: 'key7',
                label: '衍生业务开票补充',
                type: 'multiple',
                options: ['玻璃宝', '精品配件', '二手车服务费', '承保服务', '上牌', '综合服务费', '其他',],
                required: true
            },
            {
                key: 'key8',
                label: '是否按揭',
                type: 'picker',
                options: ['是', '否'],
            },
            {
                key: 'key9',
                label: '放贷书',
                type: 'upload'
            },
            {
                key: 'key10',
                label: '是否二手车抵车款',
                type: 'picker',
                options: ['是', '否'],
            },
            {
                key: 'key11',
                label: '二手车收购合同',
                type: 'upload',
                required: true
            },
            {
                key: 'key12',
                label: '销售合同/订购合同',
                type: 'upload',
            },
            {
                key: 'key13',
                label: '维修结算单',
                type: 'upload',
            },
            {
                key: 'key14',
                label: '是否事故车>=3000',
                type: 'picker',
                options: ['是', '否'],
                required: true
            },
            {
                key: 'key15',
                label: '事故定损明细单',
                type: 'upload',
                required: true
            },
            {
                key: 'key16',
                label: '索赔开票通知单',
                type: 'upload',
                required: true
            },
            {
                key: 'key17',
                label: '精品配件明细（仅Excel）',
                type: 'upload',
                required: true
            },
            {
                key: 'key18',
                label: '业务类型-其他业务-补充内容',
                type: 'multiple',
                options: ['废品费用', '质损', '洗车', '充电桩电费', '水', '电', '物业', '租赁', '资产处置'],
                required: true
            },
            {
                key: 'key19',
                label: '其他业务开票补充',
                type: 'multiple',
                options: ['租赁', '物业', '水', '电', '废品废油', '洗车', '充电桩电费', '质损', '其他'],
                required: true
            },
            {
                key: 'key20',
                label: '对账明细/其他相关资料',
                type: 'upload',

            },
            {
                key: 'key22',
                label: '开具发票类型',
                options: ['增值税专用发票', '普通发票'],
                type: 'picker',
                required: true
            },

            {
                key: 'key21',
                label: '客户开票资料',
                type: 'picker',
                options: ['资料1', '资料2'],
                required: true
            },
            {
                key: 'key23',
                label: '购买方名称',
                type: 'input',
                required: true
            },
            {
                key: 'key24',
                label: '购买方纳税识别号',
                type: 'input',
                required: true
            },
            {
                key: 'key25',
                label: '购买方地址、电话',
                type: 'input',
                required: true
            },
            {
                key: 'key26',
                label: '购买方开户行、账号',
                type: 'input',
                required: true
            },
            {
                key: 'key27',
                label: '收款方式',
                type: 'input',
                required: true
            },
            {
                key: 'key27',
                label: '收款凭证(回单/pos小票/转账记录等)',
                type: 'upload',
                required: true
            },
            {
                key: 'key28',
                label: '邮箱',
                type: 'input',
                required: true
            },
        ]
    },

]

class InvoiceForm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            // 初始化所有表单字段
            ...formConfig.reduce((acc, section) => {
                section.fields.forEach(field => {
                    const { defaultValue = '' } = field
                    if (field.type === 'upload') {
                        acc[field.key] = defaultValue.length ? defaultValue : []
                    } else if (field.type === 'picker') {
                        acc[field.key] = defaultValue
                    } else {
                        acc[field.key] = defaultValue
                    }
                })
                return acc
            }, {})
        }


    }

    // 更新条件检查器

    // 处理输入变化
    handleInputChange = (key, value) => {
        this.setState({
            [key]: value
        })
    }

    // 处理选择器变化
    handlePickerChange = (key, value) => {
        this.setState({
            [key]: value
        })
    }

    // 处理文件上传
    handleFileUpload = async (key) => {
        try {
            const res = await Taro.chooseImage({
                count: 9,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera']
            })

            const newFiles = [...(this.state[key] || []), ...res.tempFilePaths]
            this.handleInputChange(key, newFiles)
        } catch (error) {
            console.error('上传文件失败:', error)
        }
    }
    // 在组件中添加处理多选变化的方法
    handleMultipleChange = (key, selectedValues) => {
        this.setState({
            [key]: selectedValues
        })
    }
    // 移除已上传文件
    handleRemoveFile = (key, index) => {
        const files = [...this.state[key]]
        files.splice(index, 1)
        this.handleInputChange(key, files)
    }

    // 表单提交
    handleSubmit = (e) => {
        const formData = e.detail.value
        console.log('表单提交数据:', {
            ...this.state,
            ...formData
        })

        // 这里可以添加表单验证
        if (this.validateForm()) {
            Taro.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 2000
            })

            // 实际业务中这里会调用API提交数据
            // this.submitFormData()
        }
    }

    // 表单验证
    validateForm = () => {
        let isValid = true
        const errors = []

        formConfig.forEach(section => {
            section.fields.forEach(field => {
                if (field.required && !this.state[field.key]) {
                    isValid = false
                    errors.push(`${field.label}为必填项`)
                }
            })
        })

        if (!isValid) {
            Taro.showToast({
                title: errors[0] || '请完善表单信息',
                icon: 'none',
                duration: 3000
            })
        }

        return isValid
    }
    // 处理身份证上传
    handleIdCardUpload = async (key, side) => {
        try {
            const res = await Taro.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera']
            })

            const filePath = res.tempFilePaths[0]
            this.setState({
                [`${key}${side.charAt(0).toUpperCase() + side.slice(1)}`]: filePath
            })

            // 如果正反面都上传了，自动触发OCR识别
            if (this.state[`${key}Front`] && this.state[`${key}Back`]) {

            }
        } catch (error) {
            console.error('上传身份证失败:', error)
            Taro.showToast({
                title: '上传失败',
                icon: 'none'
            })
        }
    }
    handleOcrImageUpload = async (key, side) => { }
    handleOcrRecognizeImage = async (key, side) => { }
    // 删除身份证图片
    handleRemoveIdCard = (key, side) => {
        this.setState({
            [`${key}${side.charAt(0).toUpperCase() + side.slice(1)}`]: ''
        })
    }

    // 渲染表单项
    renderFormField = (field) => {
        const { key, label, type, options, inputType, placeholder, required, condition, disabled } = field

        // 检查显示条件
        const shouldShow = createConditionChecker({ state: this.state, value: field })
        console.log(shouldShow, 'field')
        if (!shouldShow) return null

        const value = this.state[key]

        switch (type) {
            case 'input':
                return (
                    <View className="form-item" key={key}>
                        <Label className="label">
                            {label}
                            {required && <Text className="required">*</Text>}
                        </Label>
                        <Input
                            type={inputType || 'text'}
                            placeholder={placeholder || `请输入${label}`}
                            value={value}
                            disabled={disabled}
                            onInput={(e) => this.handleInputChange(key, e.detail.value)}
                            className="input"
                        />
                    </View>
                )

            case 'picker':
                return (
                    <View className="form-item" key={key}>
                        <Label className="label">
                            {label}
                            {required && <Text className="required">*</Text>}
                        </Label>
                        <Picker
                            mode="selector"
                            range={options}
                            onChange={(e) => this.handlePickerChange(key, options[e.detail.value])}
                        >
                            <View className="picker">
                                {value || <Text style={{ color: '#b2b2b2' }}>{`请选择${label}`}</Text>}
                            </View>
                        </Picker>
                    </View>
                )

            case 'textarea':
                return (
                    <View className="form-item" key={key}>
                        <Label className="label">
                            {label}
                            {required && <Text className="required">*</Text>}
                        </Label>
                        <Textarea
                            placeholder={placeholder || `请输入${label}`}
                            value={value}
                            onInput={(e) => this.handleInputChange(key, e.detail.value)}
                            className="textarea"
                        />
                    </View>
                )

            case 'upload':
                return (
                    <View className="form-item" key={key}>
                        <Label className="label">
                            {label}
                            {required && <Text className="required">*</Text>}
                        </Label>
                        <View className="upload-container">
                            <Button
                                onClick={() => this.handleFileUpload(key)}
                                className="upload-btn"
                            >
                                上传{label}
                            </Button>
                            <View className="preview-list">
                                {value.map((file, index) => (
                                    <View key={index} className="preview-item">
                                        <Image src={file} className="preview-image" />
                                        <Button
                                            size="mini"
                                            onClick={() => this.handleRemoveFile(key, index)}
                                            className="remove-btn"
                                        >
                                            删除
                                        </Button>
                                    </View>
                                ))}
                            </View>
                        </View>
                    </View>
                )
            case 'multiple': // 新增多选组件
                return (
                    <View className="form-item" key={key}>
                        <Label className="label">
                            {label}
                            {required && <Text className="required">*</Text>}
                        </Label>
                        <View className="multiple-container">
                            <CheckboxGroup
                                onChange={(e) => this.handleMultipleChange(key, e.detail.value)}
                            >
                                <View className="checkbox-group">
                                    {options.map((option, index) => (
                                        <Label
                                            className="checkbox-label"
                                            key={index}
                                            for={`checkbox-${key}-${index}`}
                                        >
                                            <View className="checkbox-item">
                                                <Checkbox
                                                    id={`checkbox-${key}-${index}`}
                                                    value={option}
                                                    checked={value.includes(option)}
                                                    className="checkbox"
                                                />
                                                <Text className="checkbox-text">{option}</Text>
                                            </View>
                                        </Label>
                                    ))}
                                </View>
                            </CheckboxGroup>
                            {value.includes('其他') && (
                                <View className="other-input-container">
                                    <Input
                                        placeholder={'请输入其他内容'}
                                        value={this.state[`${key}Other`] || ''}
                                        onInput={(e) => this.handleInputChange(`${key}Other`, e.detail.value)}
                                        className="other-input"
                                    />
                                </View>
                            )}
                        </View>
                    </View>
                )
            case 'idCardUpload': // 身份证正反面上传组件
                return (
                    <View className="form-item" key={key}>
                        <Label className="label">
                            {label}
                            {required && <Text className="required">*</Text>}
                        </Label>
                        <View className="id-card-upload-container">
                            <View className="id-card-sides">
                                {/* 身份证正面 */}
                                <View className="id-card-side">
                                    <Text className="side-label">身份证正面</Text>
                                    <View className="upload-area">
                                        {!this.state[`${key}Front`] ? (
                                            <Button
                                                onClick={() => this.handleIdCardUpload(key, 'front')}
                                                className="upload-btn id-card-btn"
                                            >
                                                <Text className="upload-icon">📷</Text>
                                                <Text className="upload-text">上传正面</Text>
                                            </Button>
                                        ) : (
                                            <View className="preview-container">
                                                <Image src={this.state[`${key}Front`]} className="id-card-image" />
                                                <View className="preview-actions">
                                                    <Button
                                                        size="mini"
                                                        onClick={() => this.handleIdCardUpload(key, 'front')}
                                                        className="reupload-btn"
                                                    >
                                                        重新上传
                                                    </Button>
                                                    <Button
                                                        size="mini"
                                                        onClick={() => this.handleRemoveIdCard(key, 'front')}
                                                        className="remove-btn"
                                                    >
                                                        删除
                                                    </Button>
                                                </View>
                                            </View>
                                        )}
                                    </View>
                                </View>

                                {/* 身份证反面 */}
                                <View className="id-card-side">
                                    <Text className="side-label">身份证反面</Text>
                                    <View className="upload-area">
                                        {!this.state[`${key}Back`] ? (
                                            <Button
                                                onClick={() => this.handleIdCardUpload(key, 'back')}
                                                className="upload-btn id-card-btn"
                                            >
                                                <Text className="upload-icon">📷</Text>
                                                <Text className="upload-text">上传反面</Text>
                                            </Button>
                                        ) : (
                                            <View className="preview-container">
                                                <Image src={this.state[`${key}Back`]} className="id-card-image" />
                                                <View className="preview-actions">
                                                    <Button
                                                        size="mini"
                                                        onClick={() => this.handleIdCardUpload(key, 'back')}
                                                        className="reupload-btn"
                                                    >
                                                        重新上传
                                                    </Button>
                                                    <Button
                                                        size="mini"
                                                        onClick={() => this.handleRemoveIdCard(key, 'back')}
                                                        className="remove-btn"
                                                    >
                                                        删除
                                                    </Button>
                                                </View>
                                            </View>
                                        )}
                                    </View>
                                </View>
                            </View>

                            {/* OCR识别状态显示 */}
                            {this.state[`${key}OcrLoading`] && (
                                <View className="ocr-loading">
                                    <Text className="loading-text">正在识别身份证信息...</Text>
                                </View>
                            )}
                        </View>
                    </View>
                )

            case 'ocrImageUpload': // 图片OCR识别组件
                return (
                    <View className="form-item" key={key}>
                        <Label className="label">
                            {label}
                            {required && <Text className="required">*</Text>}
                        </Label>
                        <View className="ocr-upload-container">
                            <View className="upload-section">
                                {!this.state[key] ? (
                                    <Button
                                        onClick={() => this.handleOcrImageUpload(key)}
                                        className="upload-btn ocr-upload-btn"
                                    >
                                        <Text className="upload-icon">🔍</Text>
                                        <Text className="upload-text">上传图片并识别</Text>
                                    </Button>
                                ) : (
                                    <View className="preview-with-action">
                                        <Image src={this.state[key]} className="ocr-preview-image" />
                                        <View className="preview-actions">
                                            <Button
                                                size="mini"
                                                onClick={() => this.handleOcrImageUpload(key)}
                                                className="reupload-btn"
                                            >
                                                重新上传
                                            </Button>
                                            <Button
                                                size="mini"
                                                onClick={() => this.handleInputChange(key, '')}
                                                className="remove-btn"
                                            >
                                                删除
                                            </Button>
                                            <Button
                                                size="mini"
                                                onClick={() => this.handleOcrRecognizeImage(key)}
                                                className="ocr-recognize-btn"
                                                loading={this.state[`${key}OcrLoading`]}
                                            >
                                                {this.state[`${key}OcrLoading`] ? '识别中...' : '重新识别'}
                                            </Button>
                                        </View>
                                    </View>
                                )}
                            </View>

                            {/* OCR识别状态显示 */}
                            {this.state[`${key}OcrLoading`] && (
                                <View className="ocr-loading">
                                    <Text className="loading-text">正在识别图片信息...</Text>
                                </View>
                            )}

                            {/* OCR识别结果 */}
                            {this.state[`${key}OcrResult`] && (
                                <View className="ocr-result-container">
                                    <Text className="ocr-result-title">识别结果：</Text>
                                    <View className="ocr-result-fields">
                                        {Object.entries(this.state[`${key}OcrResult`]).map(([fieldKey, fieldValue]) => (
                                            <View key={fieldKey} className="ocr-result-field">
                                                <Text className="field-label">{this.getOcrFieldLabel(fieldKey)}：</Text>
                                                <Text className="field-value">{fieldValue}</Text>
                                            </View>
                                        ))}
                                    </View>
                                    <Button
                                        onClick={() => this.applyOcrResult(key)}
                                        className="apply-ocr-btn"
                                    >
                                        应用到表单
                                    </Button>
                                </View>
                            )}
                        </View>
                    </View>
                )
            default:
                return null
        }
    }

    // 渲染表单区块
    renderFormSection = (sectionConfig, index) => {
        const visibleFields = sectionConfig.fields
            .map(field => this.renderFormField(field))
        return (
            <View className="form-section" key={index}>
                <View className="section-header">
                    <Text className="section-title">{sectionConfig.section}</Text>
                </View>
                {visibleFields}
            </View>
        )
    }

    render() {
        return (
            <View className="invoice-form">
                <ScrollView scrollY className="form-scroll">
                    <Form onSubmit={this.handleSubmit}>
                        {formConfig.map(this.renderFormSection)}

                        <View className="form-actions">
                            <Button
                                formType="submit"
                                type="primary"
                                className="submit-btn"
                            >
                                提交申请
                            </Button>
                        </View>
                    </Form>
                </ScrollView>
            </View>
        )
    }
}

export default InvoiceForm